package com.yunquan.ohana.base.ui

import android.app.Application
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.LifecycleOwner
import com.trello.rxlifecycle4.LifecycleProvider
import com.yunquan.ohana.base.binding.command.BindingAction
import com.yunquan.ohana.base.binding.command.BindingCommand
import com.yunquan.ohana.base.bus.RxBus
import com.yunquan.ohana.base.bus.RxSubscriptions
import com.yunquan.ohana.base.ui.inter.IBaseViewModel
import com.yunquan.ohana.entity.EventEntity
import com.yunquan.ohana.utils.L
import io.reactivex.rxjava3.disposables.CompositeDisposable
import io.reactivex.rxjava3.disposables.Disposable
import io.reactivex.rxjava3.functions.Consumer
import java.lang.ref.WeakReference


object ParameterField {
    var CLASS: String = "CLASS"
    var CANONICAL_NAME: String = "CANONICAL_NAME"
    var BUNDLE: String = "BUNDLE"
}

open class BaseViewModel(application: Application) : AndroidViewModel(application), IBaseViewModel, Consumer<Disposable> {

    private var uc: UIChangeLiveData? = null
    private var lifecycle: WeakReference<LifecycleProvider<*>>? = null
    private var mCompositeDisposable: CompositeDisposable? = null
    private var mSubscription: Disposable? = null
    private val mainHandler = Handler(Looper.getMainLooper())

    init {
        mCompositeDisposable = CompositeDisposable()
    }

    //返回事件
    var onBackClick = BindingCommand<Any>(object : BindingAction {
        override fun call() {
            finish()
        }
    })

    open fun addSubscribe(disposable: Disposable) {
        if (mCompositeDisposable == null) {
            mCompositeDisposable = CompositeDisposable()
        }
        mCompositeDisposable?.add(disposable)
    }

    /**
     * 注入RxLifecycle生命周期
     *
     * @param lifecycle
     */
    fun injectLifecycleProvider(lifecycle: LifecycleProvider<*>) {
        this.lifecycle = WeakReference(lifecycle)
    }

    fun getLifecycleProvider(): LifecycleProvider<*>? {
        return this.lifecycle?.get()
    }

    fun getUIChangeLiveData(): UIChangeLiveData {
        if (uc == null) {
            uc = UIChangeLiveData()
        }
        return uc!!
    }

    fun showLoading() {
        showLoading("Loading...")
    }

    fun showLoading(msg: String) {
        uc?.showDialogEvent?.postValue(msg)
    }

    fun hideLoading() {
        uc?.dismissDialogEvent?.call()
    }

    /**
     * 跳转页面
     *
     * @param clz 所跳转的目的Activity类
     */
    fun startActivity(clz: Class<*>) {
        startActivity(clz, null)
    }

    /**
     * 跳转页面
     *
     * @param clz    所跳转的目的Activity类
     * @param bundle 跳转所携带的信息
     */
    fun startActivity(clz: Class<*>, bundle: Bundle?) {
        val params = HashMap<String, Any>()
        params[ParameterField.CLASS] = clz
        bundle?.let {
            params[ParameterField.BUNDLE] = bundle
        }
        uc?.startActivityEvent?.postValue(params)
    }

    /**
     * 带返回值跳转
     */
    fun startActivityResult(clz: Class<*>) {
        startActivityResult(clz, null)
    }

    /**
     * 带返回值跳转
     */
    fun startActivityResult(clz: Class<*>, bundle: Bundle?) {
        val params = HashMap<String, Any>()
        params[ParameterField.CLASS] = clz
        bundle?.let {
            params[ParameterField.BUNDLE] = bundle
        }
        uc?.startActivityForResultEvent?.postValue(params)
    }

    /**
     * 关闭界面
     */
    fun finish() {
        uc?.finishEvent?.call()
    }

    /**
     * 返回上一层
     */
    fun onBackPressed() {
        uc?.onBackPressedEvent?.call()
    }


    override fun accept(value: Disposable) {
        addSubscribe(value)
    }

    override fun onCleared() {
        super.onCleared()
        //ViewModel销毁时会执行，同时取消所有异步任务
        mCompositeDisposable?.clear();
    }

    override fun onCreate(owner: LifecycleOwner) {
        super.onCreate(owner)
    }

    override fun onDestroy(owner: LifecycleOwner) {
        super.onDestroy(owner)
    }

    override fun onPause(owner: LifecycleOwner) {
        super.onPause(owner)
    }

    override fun onResume(owner: LifecycleOwner) {
        super.onResume(owner)
    }

    override fun onStart(owner: LifecycleOwner) {
        super.onStart(owner)
    }

    override fun onStop(owner: LifecycleOwner) {
        super.onStop(owner)
    }

    override fun registerRxBus() {
        mSubscription = RxBus.getDefault().toObservable(EventEntity::class.java)
            .subscribe({ event ->
                mainHandler.post {
                    onEvent(event)
                }
            }, { throwable ->
                L.e("RxBus 接收报错", throwable)
            })
        RxSubscriptions.add(mSubscription)
    }

    override fun removeRxBus() {
        RxSubscriptions.remove(mSubscription)
    }

    open fun onEvent(event: EventEntity) {

    }
}
